// src/components/StockPredict.js
import React, { useState, useEffect } from 'react';
import { Card, Spin, message ,Table, Empty} from 'antd';
import { $updateStockHistory } from '../../api/stockPredictApi';

const StockPredict = () => {
  const [loading, setLoading] = useState(false);
  const [predictions, setPredictions] = useState(null);

  useEffect(() => {
    const fetchPredictions = async () => {
      setLoading(true);
      try {
        const response = await $updateStockHistory(); // 
        //console.log(response)
        console.log('yes');
        setPredictions(response); // 直接使用 response.data
      } catch (err) {
        console.error('预测失败', err);
        message.error('预测失败，请稍后再试');
      } finally {
        setLoading(false);
      }
    };
    fetchPredictions();
  }, []);

  // 辅助函数：格式化日期（去掉时间部分）
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
    });
  };

  return (
  <Card 
    title="股票价格预测" 
    extra={null}
  >
    {predictions ? (
      <div>
        <h3>预测结果</h3>
        {predictions.length > 0 ? (
          <div style={{ maxHeight: 500, overflowY: 'auto' }}>
            {Object.entries(
              predictions.reduce((acc, item) => {
                if (!acc[item.ticker]) acc[item.ticker] = [];
                acc[item.ticker].push(item);
                return acc;
              }, {})
            ).map(([ticker, data]) => (
              <div key={ticker} style={{ marginBottom: 16 }}>
                <strong style={{ fontSize: 16 }}>{ticker}</strong>
                <Table
                  size="small"
                  columns={[
                    {
                      title: '日期',
                      dataIndex: 'date',
                      key: 'date',
                      render: (date) => formatDate(date),
                    },
                    {
                      title: '预测收盘价',
                      dataIndex: 'predicted_close',
                      key: 'predicted_close',
                      render: (price) => price.toFixed(2),
                    },
                  ]}
                  dataSource={data}
                  pagination={false}
                  rowKey={(record) => `${ticker}-${record.date}`}
                />
              </div>
            ))}
          </div>
        ) : (
          <Empty description="暂无预测数据" />
        )}
      </div>
    ) : (
      <div style={{ textAlign: 'center', padding: 24 }}>
        {loading ? <Spin tip="数据加载中..." /> : <Empty description="暂无数据" />}
      </div>
    )}
  </Card>
)
}

export default StockPredict;